package jp.joogoo.web.controller;

import java.io.PrintWriter;
import java.util.List;

import jp.joogoo.web.meta.M_joogooMeta;
import jp.joogoo.web.meta.M_serviceMeta;
import jp.joogoo.web.model.M_joogoo;
import jp.joogoo.web.model.M_service;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.json.JSONStringer;

public class ServicesController extends Controller {
    private static final M_serviceMeta serviceMeta = new M_serviceMeta();
    private static final M_joogooMeta meta = new M_joogooMeta();

    
    @Override
    protected Navigation run() throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        
        // TODO リクエストでユーザートークンを受け取るようにして、認証済みサービスは表示しないようにする。
        List<M_service> services = Datastore.query(serviceMeta).asList();

        if (user != null) {
            List<M_joogoo> joogoos =
                Datastore.query(meta).filter(meta.userId.equal(user.getUserId())).asList();
            for(M_joogoo joogoo: joogoos){
                services.remove(joogoo.getMServiceRef().getModel());
            }
        }
        
        JSONStringer jsonService = new JSONStringer();
        jsonService.array();        
        if (services != null && services.size() > 0) {
            for (M_service service : services) {
                jsonService.object()
                .key("key")
                .value(KeyFactory.keyToString(service.getKey()))
                .key("name")
                .value(service.getServiceName())
                .endObject();
            } 
        }
        jsonService.endArray();

        PrintWriter writer = response.getWriter();
        writer.print(jsonService.toString());
        response.flushBuffer();

        return null;
    }

}
